package com.telchina.rcbg.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.telchina.common.core.domain.AjaxResult;
import com.telchina.common.core.domain.entity.SysDicInfo;
import com.telchina.common.core.domain.entity.SysOrg;
import com.telchina.common.core.domain.entity.SysUser;
import com.telchina.common.domain.WoAttachment;
import com.telchina.common.service.IWoAttachmentService;
import com.telchina.common.utils.SecurityUtils;
import com.telchina.framework.system.service.ISysOrgService;
import com.telchina.framework.system.service.ISysUserService;
import com.telchina.rcbg.domain.KnowledgeInfo;
import com.telchina.rcbg.domain.ProclamationInfo;
import com.telchina.rcbg.mapper.ProclamationInfoMapper;
import com.telchina.rcbg.service.IProclamationInfoService;
import com.telchina.utils.StrUtil;
import com.telchina.workorder.third.service.SystemThirdService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Auther: zlm
 * @Date: 2023/3/27
 * @Description: com.telchina.rcbg.service.impl
 * @Version: 1.0
 */
@Service
public class ProclamationInfoServiceImpl extends ServiceImpl<ProclamationInfoMapper, ProclamationInfo> implements IProclamationInfoService {

    @Resource
    private IWoAttachmentService attachmentService;
    @Resource
    private SystemThirdService systemThirdService;

    private static final String STATUS_0 = "0"; // 草稿
    private static final String STATUS_1 = "1"; // 已发布
    private static final String STATUS_2 = "2"; // 归档

    @Override
    public boolean saveWithLoginUser(ProclamationInfo info) {
        // 前端传递发布人和发布单位，不再从后端获取
        if (StringUtils.isEmpty(info.getIssuer())) {
            throw new RuntimeException("发布人为空");
        }
        if (StringUtils.isEmpty(info.getIssueDepart())) {
            throw new RuntimeException("发布单位为空");
        }
        // 提起纯文本，用于搜索
        info.setContentText(StrUtil.htmlToText(info.getContent()));
        info.setIssueTime(STATUS_1.equals(info.getStatus()) ? new Date() : null);
        info.setCreateBy(info.getIssuer());
        info.setCreateTime(new Date());
        info.setUpdateBy(info.getIssuer());
        info.setUpdateTime(info.getCreateTime());
        return save(info);
    }

    @Override
    public boolean modifyById(ProclamationInfo info) {
        info.setContentText(StrUtil.htmlToText(info.getContent()));
        if (STATUS_1.equals(info.getStatus())) {
            info.setIssueTime(new Date());
        } else if (STATUS_0.equals(info.getStatus())) {
            info.setIssueTime(null);
        }
        info.setUpdateBy(SecurityUtils.getUserId());
        info.setUpdateTime(info.getCreateTime());
        return updateById(info);
    }

    /**
     * 分页查询
     *
     * @param pageNum    页码
     * @param pageSize   每页条数
     * @param queryParam 查询条件
     * @return
     */
    @Override
    public IPage<ProclamationInfo> pageList(Integer pageNum, Integer pageSize, ProclamationInfo queryParam) {
        // 获取登录用户所在部门
        SysOrg org = systemThirdService.getLoginUseDeptByUserId(SecurityUtils.getUserId());
        if (Objects.isNull(org)) {
            throw new RuntimeException("获取登录人所在单位失败");
        }
        queryParam.setIssueDepart(org.getId());
        IPage<ProclamationInfo> page = new Page<>(pageNum, pageSize);
        List<ProclamationInfo> dataList = baseMapper.pageList(page, queryParam);
        if (!dataList.isEmpty()) {
            // 发布部门
            List<SysOrg> issueDepartList = systemThirdService.getDeptIdInfoList(dataList.stream().map(ProclamationInfo::getIssueDepart).distinct().collect(Collectors.toList()));
            for (ProclamationInfo proclamationInfo : dataList) {
                // 发布部门赋值
                for (SysOrg sysOrg : issueDepartList) {
                    if (Objects.equals(proclamationInfo.getIssueDepart(), sysOrg.getId())) {
                        proclamationInfo.setIssueDepartName(sysOrg.getName());
                        break;
                    }
                }
            }
        }
        return page.setRecords(dataList);
    }

    /**
     * 获取详情，包含附件
     *
     * @param id 主键
     * @return
     */
    @Override
    public ProclamationInfo getByIdWithAttachment(String id) {
        ProclamationInfo info = getById(id);
        if (Objects.nonNull(info)) {
            // 查询发布人
            SysUser user = systemThirdService.getSysUserInfo(info.getIssuer());
            if (Objects.nonNull(user)) info.setIssuerName(user.getLoginName());
            // 查询发布部门和发布范围
            String issueDepart = info.getIssueDepart();
            List<SysOrg> departs = systemThirdService.getDeptIdInfoList(Arrays.asList((info.getIssueScope() + "," + issueDepart).split(",")));
            StringJoiner sj = new StringJoiner(",");
            for (SysOrg depart : departs) {
                if (issueDepart.equals(depart.getId())) {
                    info.setIssueDepartName(depart.getName());
                } else {
                    sj.add(depart.getName());
                }
            }
            info.setIssueScopeName(sj.toString());
            // 查询附件
            info.setAttachmentList(attachmentService.list(Wrappers.<WoAttachment>lambdaQuery().eq(WoAttachment::getBussId, id)));
        }
        return info;
    }

    @Override
    @Transactional
    public boolean removeByIdWithAttachment(String id) {
        // 删除公告和附件
        return removeById(id) && attachmentService.remove(Wrappers.<WoAttachment>lambdaUpdate().eq(WoAttachment::getBussId, id));
    }
}
